<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>AJAX封装_设置默认值</h1>
    <input type="button" value="获取响应数据get" onclick="get_data()">
    <input type="button" value="获取响应数据post" onclick="get_data_post()">
    <script>
        function AJAX(options){
            /**
             *options:
             * type:请求方式
             * url:请求地址
             * data:请求的参数，默认是json
             * success：请求成功后，如何处理
             * error：请求失败后，处理
             */
            let defaults={
                type:'get',
                url:'',
                success:()=>{},
                error:() =>{}
            }
            //会把option中的内容覆盖defaults
            Object.assign(defaults,options)

            let xhr = new XMLHttpRequest()

            let params = ''
            for(let key in defaults.data){
                value = defaults.data[key]
                params = params+key+'='+value+'&'
            }
            //去掉最后一个&
            params = params.substring(0,params.length-1)
            if(defaults.type === 'get'){
                defaults.url = defaults.url + '?' + params
            }
            xhr.open(defaults.type,defaults.url)
            if(defaults.type === 'post'){
                xhr.setRequestHeader('Content-Type','application/x-form-urlencoded')
                xhr.send(params)
            }else{
                xhr.send()
            }
            xhr.onreadystatechange=() =>{
                if(xhr.readyState===4){
                    if(xhr.status ===200){
                        defaults.success(xhr.responseText)
                    }else{
                        defaults.error(xhr.status)
                    }
                }
            }
            xhr.onerror = () =>{
                defaults.error('网络错误')
            }
        }

        function get_data(){
            AJAX({
                type:'get',
                url:'http://httpbin.org/get',
                data:{'name':'sxt','pwd':'123'},
                success:function(data){
                    console.log(data)
                },
                error:(data)=>{
                    console.log(data)
                }
            })
        }

        function get_data_post(){
            AJAX({
                type:'post',
                url:'http://httpbin.org/post',
                data:{'name':'sxt','pwd':'123'}
            })
        }
    </script>
</body>
</html>